/*
 *Copyright(c) 2021 Shenzhen Kaihong Digital Industry DevelopmentCo.,Ltd
 *Licensed under the Apache License,Version2.0(the"License");
 *you may not use this file except in compliance with the License.
 *You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,software
 * distributed under the License is distributed on an "AS IS"BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.chinasoft.service.impl;


import com.chinasoft.bean.po.PushStrategyPO;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.*;
import java.util.Properties;


@Component
public class SendEmailServiceImpl {

    @Value("${mail.transport.protocol}")
    private  String protocol;

    @Value("${mail.smtp.host}")
    private  String host;

    @Value("${mail.smtp.port}")
    private  int port;
    @Value("${mail.smtp.auth}")
    private  String auth;

    @Value("${mail.smtp.ssl.enable}")
    private  String sslEnable;

    @Value("${mail.debug}")
    private  String debug;

    @Value("${mail.send.from}")
    private  String from;

    @Value("${mail.smtp.server.user}")
    private  String user;

    @Value("${mail.smtp.server.password}")
    private  String password;

    private static final Logger logger = LoggerFactory.getLogger(SendEmailServiceImpl.class);


    public void send(PushStrategyPO pushStrategyPO) throws  Exception {
        Properties properties = new Properties();
        logger.info("64738264738264738   "+protocol);
        properties.put("mail.transport.protocol", protocol);//协议
//        properties.put("mail.smtp.host","smtp.qq.com");//主机名
        properties.put("mail.smtp.host", host);
        properties.put("mail.smtp.port", port);//端口号
        properties.put("mail.smtp.auth",auth );
        properties.put("mail.smtp.ssl.enable",sslEnable);//设置ssl安全连接
        properties.put("mail.debug", debug);//显示debug信息

            //会话对象
            Session session = Session.getInstance(properties);
            //获取邮件对象
            Message message = new MimeMessage(session);
            //设置发件人邮箱地址
            message.setFrom(new InternetAddress(from));
            //设置收件人邮箱地址
            String recipient = pushStrategyPO.getRecipient();
            InternetAddress[] internetAddresses1 = buildArray(recipient);
            message.setRecipients(Message.RecipientType.TO, internetAddresses1
            );

            String cc = pushStrategyPO.getCC();
            //设置抄送人邮箱地址
            if (!StringUtils.isEmpty(cc)) {
                InternetAddress[] internetAddresses = buildArray(cc);
                message.setRecipients(Message.RecipientType.CC, internetAddresses);
            }
            //设置邮件标题
            message.setSubject(pushStrategyPO.getSubmit());
            MimeBodyPart mimeBodyPart = new MimeBodyPart();

            mimeBodyPart.setContent(pushStrategyPO.getContent(), "text/html;charset=utf-8");
            MimeMultipart mm = new MimeMultipart();
            mm.addBodyPart(mimeBodyPart);
            //如果为空设置
        if (!StringUtils.isBlank(pushStrategyPO.getPath())){
            MimeBodyPart body1 = new MimeBodyPart(); //附件1
            body1.setDataHandler(new DataHandler(new FileDataSource(pushStrategyPO.getPath())));
            body1.setFileName(MimeUtility.encodeText(pushStrategyPO.getFileName()));
            mm.addBodyPart(body1);
        }

            message.setContent(mm);
            //得到邮箱对象
            Transport transport = session.getTransport();
            //连接smtp服务器
            transport.connect(user, password);
            //发送邮件
            transport.sendMessage(message, message.getAllRecipients());
            //关闭邮件对象
            transport.close();
    }

    private  InternetAddress[] buildArray(String emails) throws AddressException {
        String[] emailArr = emails.trim().split(";");
        InternetAddress[] internetAddresses = new InternetAddress[emailArr.length];
        for (int i = 0; i < emailArr.length; i++) {
            internetAddresses[i] = new InternetAddress(emailArr[i]);
        }

        return internetAddresses;
    }
}
